package cn.com.shaom.learning.sb.web.ssl;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ClassName: CustomTomcatConfig
 * Description: http 自动转向 https 配置
 * 需要配置 TomcatEmbeddedServletContainerFactory ,并且添加 Tomcat 的 connector 来实现
 * Date: 2017/12/22 16:19 【需求编号】
 *
 * @author Shaom
 * @version V1.0.0
 */
@Configuration
public class CustomTomcatConfig {

    /**
     * 自定义的 TomcatEmbeddedServletContainerFactory
     *
     * @return
     */
    @Bean
    public EmbeddedServletContainerFactory servletContainerFactory() {
        TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection securityCollection = new SecurityCollection();
                securityCollection.addPattern("/*");
                securityConstraint.addCollection(securityCollection);
                context.addConstraint(securityConstraint);
            }
        };

        // 添加自定义tomcat 的Connector
        factory.addAdditionalTomcatConnectors(httpConnector());
        return factory;
    }

    /**
     * 定义tomcat 的Connector
     *
     * @return
     */
    @Bean
    public Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8080);
        connector.setSecure(false);
        connector.setRedirectPort(8443);

        Http11NioProtocol http11NioProtocol = (Http11NioProtocol) connector.getProtocolHandler();
        //设置最大线程数
        http11NioProtocol.setMaxThreads(100);
        //设置初始线程数  最小空闲线程数
        http11NioProtocol.setMinSpareThreads(20);
        //设置超时
        http11NioProtocol.setConnectionTimeout(5000);

        return connector;
    }
}
